package org.douxiaoban.client.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.mobclick.android.MobclickAgent;
import org.douxiaoban.client.R;
import org.douxiaoban.client.adapter.CollectionListAdapter;
import org.douxiaoban.client.api.CollectionRecord;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.model.BundleSerializable;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.util.WorkspaceView;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle;

/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-6-5
 * Time: 下午1:09
 */
public class CollectionMovieListActivity extends BaseActivity
        implements WorkspaceView.ScrollToScreenCallback{
       private ThreadTool _threadTool;
       private WorkspaceView _scrollView;
       private LayoutInflater _inflater;
       private CollectionMovieListActivity _this;

       private LinearLayout _book_progressLay;
       private TitleStyle _title_style;
        private PopupRecommend _popup_recommend;
       //wish
       private ListView _book_wish_listview;
       private CollectionListAdapter _book_wish_adapter;
       private int _book_wish_page = 1;
       private Boolean _book_wish_is_loading_more = false;
       private Boolean _book_wish_is_no_more = false;
       private View _book_foot_view;

       //readed
       private ListView _book_readed_listview;
       private CollectionListAdapter _book_readed_adapter;
       private int _book_readed_page = 1;
       private Boolean _book_readed_is_loading_more = false;
       private Boolean _book_readed_is_no_more = false;

       private String _curent_user_id;
       private View viewReadedList;
       private View viewWishList ;

    public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           _this = this;
           _scrollView = new WorkspaceView(this, null);
           _scrollView.setTouchSlop(32);

            _inflater =
                   (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        _curent_user_id =  getIntent().getStringExtra(Assistant.KEY_USER_ID);
        if(_curent_user_id==null || _curent_user_id.equals(""))
            _curent_user_id = App.userId;

           resignViewCompent();
           startThreadDownloadData(Assistant.STATUS_MOVICE_WATCHED,_book_readed_page);
           resignScrollListener();
           _scrollView.setScrollToScreenCallback(this);

        _popup_recommend = new PopupRecommend(this);
            //custom title
            requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
           this.setContentView(_scrollView);
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);

           //resgin title
            _title_style = new TitleStyle(this);
            _title_style.initTitleStyle();
            _title_style.initPageController(2,1);
       }

       private void resignViewCompent(){
            viewWishList = _inflater.inflate(R.layout.collection_list,null);
           viewReadedList = _inflater.inflate(R.layout.collection_list,null);

           _book_progressLay = (LinearLayout)viewWishList.findViewById(R.id.collection_progress);
           _book_foot_view = _inflater.inflate(R.layout.list_view_foot,null);

           //wish
           _book_wish_listview = (ListView)viewWishList.findViewById(R.id.book_listview);
           _book_wish_adapter = new CollectionListAdapter(this,_handler,Assistant.STATUS_BOOK_WISH,_book_wish_listview);
           _book_wish_listview.addFooterView(_book_foot_view);
           _book_wish_listview.setAdapter(_book_wish_adapter);

           //readed
           _book_readed_listview = (ListView)viewReadedList.findViewById(R.id.book_listview);
           _book_readed_adapter = new CollectionListAdapter(this,_handler,Assistant.STATUS_BOOK_READED,_book_readed_listview);
           _book_readed_listview.addFooterView(_book_foot_view);
           _book_readed_listview.setAdapter(_book_readed_adapter);

           _threadTool = ThreadTool.instace(this);

           _scrollView.addView(viewReadedList);
           _scrollView.addView(viewWishList);

       }

       private void resignScrollListener(){
           _book_readed_listview.setOnItemClickListener(
                                       new AbsListView.OnItemClickListener(){
               @Override
               public void onItemClick(AdapterView<?> adapterView,
                                       View view, int position, long l) {

                   /**
                    * 传入subject 的id,分类,与subject record对象到内容页
                    */
                   Intent intent = new Intent(CollectionMovieListActivity.this,
                           CollectionSubjectActivity.class);

                   intent.putExtra(Assistant.KEY_OF_INTENT_ID,
                           _book_readed_adapter._crs.get(position).id);
                   intent.putExtra(Assistant.KEY_OF_INTENT_CATEGORY,
                           Assistant.STATUS_MOVICE);

                   CollectionRecord record = _book_readed_adapter._crs.get(position);

                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_RATTING,record.rating);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_TYPE,record.status);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_SUMMARY,record.summary);

                   _this.startActivity(intent);
               }
           });

           _book_wish_listview.setOnItemClickListener(
                new AbsListView.OnItemClickListener(){
                    @Override
                    public void onItemClick(AdapterView<?> adapterView,
                                       View view, int position, long l) {

                   /**
                    * 传入subject 的id,分类,与subject record对象到内容页
                    */
                   Intent intent = new Intent(CollectionMovieListActivity.this,
                           CollectionSubjectActivity.class);

                   intent.putExtra(Assistant.KEY_OF_INTENT_ID,
                           _book_wish_adapter._crs.get(position).id);
                   intent.putExtra(Assistant.KEY_OF_INTENT_CATEGORY,
                           Assistant.STATUS_MOVICE);

                   CollectionRecord record = _book_wish_adapter._crs.get(position);

                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_RATTING,record.rating);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_TYPE,record.status);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_SUMMARY,record.summary);

                   _this.startActivity(intent);
                    }
                }
           );

            _book_wish_listview.setOnScrollListener(new AbsListView.OnScrollListener(){
               @Override
               public void onScroll(AbsListView view, int firstVisibleItem,
                                    int visibleItemCount, int totalItemCount) {
                    if(firstVisibleItem > 0 && (totalItemCount-firstVisibleItem)<7
                       && !_book_wish_is_no_more && !_book_wish_is_loading_more){
                       _book_wish_page += 15;
                       _book_wish_is_loading_more = true;
                       startThreadDownloadData(Assistant.STATUS_BOOK_WISH,_book_wish_page);
                   }
               }
               @Override
               public void onScrollStateChanged(AbsListView absListView, int i) {

               }
           });



           _book_readed_listview.setOnScrollListener(new AbsListView.OnScrollListener(){
               @Override
               public void onScroll(AbsListView view, int firstVisibleItem,
                                    int visibleItemCount, int totalItemCount) {
                    if(firstVisibleItem > 0 && (totalItemCount-firstVisibleItem)<7
                       && !_book_readed_is_no_more && !_book_readed_is_loading_more){
                       _book_readed_page += 15;
                       _book_readed_is_loading_more = true;
                       startThreadDownloadData(Assistant.STATUS_MOVICE_WATCHED,_book_readed_page);
                   }
               }
               @Override
               public void onScrollStateChanged(AbsListView absListView, int i) {

               }
           });
        }

       private void startThreadDownloadData(String bookType,int page){
           //TODO: This is test data
            String category = "movie";

           _threadTool.startThreadFetchUserCollection(_curent_user_id,category,page,
                   bookType,_handler);
        }

       public void startThreadImageDownload(int position,String url,String bookType){
          _threadTool.startThreadImageDownload(bookType,url,_handler,position);
       }

       private Handler _handler = new Handler() {
           @Override
           public void handleMessage(Message msg) {
               switch (msg.what){
                   case Assistant.FETCH_BOOK_READED_DONE:
                       Bundle bundle = msg.getData();
                       BundleSerializable ser = (BundleSerializable)
                               bundle.getSerializable(Assistant.KEY_OF_COLLECTION);

                       //无更多的数据加载，删除footview，
                       if(ser.crs == null || ser.crs.size()<Assistant.PAGE_SIZE){
                           _book_readed_is_no_more = true;
                           _book_readed_listview.removeFooterView(_book_foot_view);
                           //TODO 告诉用户，已经加载到底了
                       }

                       if(_book_readed_adapter._crs == null)
                           _book_readed_adapter._crs = ser.crs;
                       else
                           _book_readed_adapter._crs.addAll(ser.crs);

                       //update title
                       if(_book_readed_adapter!=null && _book_readed_adapter._crs.size()>0)
                            _title_style.setTitle(_book_readed_adapter._crs.get(0).total_result
                            +getString(R.string.bu)+getString(R.string.title_watched));

                       _book_readed_adapter.changeData();

                       _book_readed_listview.setVisibility(View.VISIBLE);
                       viewReadedList.findViewById(R.id.collection_progress).setVisibility(View.GONE);

                       _book_readed_is_loading_more = false;
                        break;

                   case Assistant.FETCH_BOOK_WISH_DONE:
                          Bundle blw = msg.getData();
                       BundleSerializable sew = (BundleSerializable)
                               blw.getSerializable(Assistant.KEY_OF_COLLECTION);
                       System.out.println(sew.crs);

                       //无更多的数据加载，删除footview，
                       if(sew.crs == null || sew.crs.size()<Assistant.PAGE_SIZE){
                           _book_wish_is_no_more = true;
                           _book_wish_listview.removeFooterView(_book_foot_view);
                           //TODO 告诉用户，已经加载到底了
                       }

                       if(_book_wish_adapter._crs == null)
                           _book_wish_adapter._crs = sew.crs;
                       else
                           _book_wish_adapter._crs.addAll(sew.crs);

                       //update title
                       if(_book_wish_adapter!=null && _book_wish_adapter._crs.size()>0)
                            _title_style.setTitle(_book_wish_adapter._crs.get(0).total_result
                            +getString(R.string.bu)+getString(R.string.title_watched));

                       _book_wish_adapter.changeData();

                       _book_wish_listview.setVisibility(View.VISIBLE);
                       viewWishList.findViewById(R.id.collection_progress).setVisibility(View.GONE);

                       _book_wish_is_loading_more = false;
                       break;
                   case Assistant.FETCH_COLLECTION_FAIL:
                       _popup_recommend.showToastWindow(0,getString(R.string.load_fail));
                    finish();
                        break;
                    case Assistant.FETCH_BOOK_READED_IMAGE_DONE:
                       Bundle be = msg.getData();
                       ThreadTool.ImageSerialz is = (ThreadTool.ImageSerialz)
                               be.getSerializable(Assistant.THREAD_IMAGE_KEY);
                       _book_readed_adapter._crs.get(is.m_iPosition).icon_bitmap = is.m_bitmap;

                       _book_readed_adapter.notifyDataSetChanged();
                       break;
                    case Assistant.FETCH_BOOK_WISH_IMAGE_DONE:
                            Bundle bew = msg.getData();
                       ThreadTool.ImageSerialz isw = (ThreadTool.ImageSerialz)
                               bew.getSerializable(Assistant.THREAD_IMAGE_KEY);
                       _book_wish_adapter._crs.get(isw.m_iPosition).icon_bitmap = isw.m_bitmap;

                       _book_wish_adapter.notifyDataSetChanged();
                        break;

                   case Assistant.FETCH_IMAGE_FAIL:
                       break;
                   default:
                       break;
               }
             //  super.handleMessage(msg);
           }
       };

       @Override
       public void callback(int currentIndex) {

           switch (currentIndex){
               case Assistant.BOOK_INDEX_READED:
                   //update title
                   if(_book_readed_adapter!=null && _book_readed_adapter._crs.size()>0){
                    _title_style.setTitle(_book_readed_adapter._crs.get(0).total_result
                            +getString(R.string.bu)+getString(R.string.title_watched));
                   }else{
                       _title_style.setTitle(getString(R.string.title_watched));
                   }
                   _title_style.setCurrentPage(1);
                   break;
               case 1:
                   if(!_book_readed_is_loading_more && _book_wish_adapter._crs.size() == 0)
                    startThreadDownloadData(Assistant.STATUS_MOVICE_WISH,_book_wish_page);

                   //update title
                   if(_book_wish_adapter!=null && _book_wish_adapter._crs.size()>0){
                    _title_style.setTitle(_book_wish_adapter._crs.get(0).total_result
                            +getString(R.string.bu)+getString(R.string.title_watched_wish));
                   }else{
                     _title_style.setTitle(getString(R.string.title_watched_wish));
                   }
                   _title_style.setCurrentPage(2);
                   break;
               default:
                   break;
           }
       }

      @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();    //Super Method super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();    //Super Method super.onPause();
    }
}